<!--
* description: 试驾车订单配车
* author: wangml
* createdDate: 2020-11-12
-->
<template>
  <div class="app-container app-container-table">
    <!-- 单表格模版页面 -->
    <one-table-template
      ref="multipleTable"
      :dynamic-api-config="dynamicApiConfig"
      :dynamic-buttons="dynamicButtons"
      :dynamic-components="tableComponents"
      :dynamic-table-cols="dynamicTableCols"
      :dynamic-form-fields="formField"
      :dynamic-is-show-more-btn="true"
      :dynamic-is-show-select="true"
      :dynamic-api-style="apiStyle"
      :dynamic-page-size="10"
      :refresh-table-key="refreshTableKey"
      :callback-obj="callbackObj"
      @hiddenColData="hiddenColData"
    />
    <manual-config-car
      ref="configcar"
      :popups-visible.sync="curPopupsVisible"
      :dynamic-edit-row-data="rowData"
      @get-config-data="getConfigData"
    />
    <batch-config-car
      ref="batchConfig"
      :multiple-data="batchData"
      :popups-visible.sync="curPopupsVisible1"
    />
    <import-config-car
      ref="importCfg"
      :popups-visible.sync="exportPopups"
    />
  </div>
</template>
<script>
import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import OneTableTemplate from '@/components/templates/oneTable'
import ManualConfigCar from './ManualConfigCar'
import batchConfigCar from './batchConfigCar'
import importConfigCar from './importConfigCar'
import Vue from 'vue'
import api from '@/api/testDriver'
import commData from '../common'
import { exportExcel } from '../../../../utils/exportExcel'

export default {
  name: 'TDOrderDistributeCar',
  components: {
    OneTableTemplate,
    ManualConfigCar,
    batchConfigCar,
    // eslint-disable-next-line vue/no-unused-components
    importConfigCar
  },
  mixins: [oneTableWithViewTemplateMixins],
  // 阻塞路由预加载网格中组件的数据
  beforeRouteEnter(to, from, next) {
    Vue.prototype.$ConfigCache.CacheConfig.initData(
      // 同时加载当前页面和编辑框页面的配置
      [to.path, ''],
      function() {
        next()
      })
  },
  data() {
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path
    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])
    return {
      batchData: [],
      rowData: {},
      curPopupsVisible: false,
      curPopupsVisible1: false,
      genCodeFiled: null,
      selectList: [],
      clickRowsData: {},
      popstate: 'add',
      showdia: false,
      // 指定请求类型 可以统一在 utils/config.js中配置
      apiStyle: 'restful',
      dynamicApiConfig: api.orderDistributeCar,
      refreshTableKey: '0',
      ruleSettingShow: false,
      // table表格查询API配置对象
      // 动态组件-查询条件
      tableComponents:
          this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableComponents.length > 0
            ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableComponents
            : [
              ...commData.frontFields(2),
              ...commData.ModelOptionsNotDisabled()

            ],
      formField: null,
      // 动态组件-按钮
      dynamicButtons: this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableButtons &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableButtons.length > 0
        ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableButtons
        : [
          {
            compKey: 'btnKey1',
            type: 'primary',
            size: 'small',
            name: 'search',
            clickEvent: () => this.queryTable(1),
            text: '查询'
          },
          {
            compKey: 'btnKey2',
            type: '',
            size: 'small',
            name: 'reset',
            clickEvent: this.reset,
            text: '重置'
          },
          // {
          //   compKey: 'btnKey3',
          //   type: '',
          //   size: 'small',
          //   name: 'configCar',
          //   position: 'left',
          //   clickEvent: this.configCar,
          //   disabled: true,
          //   text: '批量手工配车'
          // },
          // {
          //   compKey: 'btnKey4',
          //   type: '',
          //   size: 'small',
          //   name: 'ReleaseConfig',
          //   position: 'left',
          //   clickEvent: this.exportConfigCar,
          //   text: '导入配车'
          // },
          // {
          //   compKey: 'btnKey5',
          //   type: '',
          //   size: 'small',
          //   name: 'confirm',
          //   position: 'left',
          //   clickEvent: this.tailConfig,
          //   text: '尾款确认',
          //   disabled: true
          // },
          {
            compKey: 'btnKey6',
            type: '',
            size: 'small',
            name: 'export',
            position: 'left',
            clickEvent: this.export,
            text: '导出'
          }
        ],
      // 动态组件-表格网格列
      dynamicTableCols: this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableCols.length > 0
        ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableCols
        : [
          {
            label: '操作',
            minWidth: 180,
            fixed: true,
            isComponent: true,
            comps: [
              {
                compKey: 'propKey1',
                labelName: '配车',
                component: () => import('@/components/org/linkButton'),
                clickEvent: (index) => this.edit(index),
                rowFileds: 'show:OrderStatus-订单已分配|合同已签署'
              },
              {
                compKey: 'propKey2',
                labelName: '解配',
                component: () => import('@/components/org/linkButton'),
                clickEvent: (index) => this.depp(index),
                rowFileds: 'show:OrderStatus-订单已配车'
              }
              // {
              //   compKey: 'propKey3',
              //   component: () => import('./showIcon'),
              //   rowFileds: 'show:OrderStatus-尾款已支付|车辆已发车',
              //   // icon: 'el-icon-success'
              // },
            ]
          },
          {
            prop: 'releaseId',
            label: '主键ID',
            hidden: true,
            alwaysHidden: true
          },
          {
            prop: 'updateControlId',
            label: '并发控制ID',
            hidden: true,
            alwaysHidden: true
          },
          {
            prop: 'saleOrderCode',
            label: '订单编号',
            width: 250
          },
          {
            prop: 'insaleOrderCode',
            label: '试驾车单号',
            width: 130
          },
          {
            prop: 'OrderStatus',
            label: '订单状态'
          },
          {
            prop: 'salePlanCode',
            label: '销售计划号'
          },
          {
            prop: 'vin',
            label: 'VIN码'
          },
          {
            prop: 'carHouseName',
            label: '仓库名称'
          },
          // {
          //   prop: 'saleOrderSign',
          //   label: '订单标签'
          // },
          {
            prop: 'orderDate',
            label: '下单日期',
            width: 140
          },
          {
            prop: 'preDeliverDate',
            label: '预计交付日期'
          },
          {
            prop: 'cityName',
            label: '交付城市'
          },
          {
            prop: 'deliveryDlrShortName',
            label: '交付门店'
          },
          {
            prop: 'dlrShortName',
            label: '体验中心'
          },
          {
            prop: 'carSeriesCN',
            label: '车系'
          },
          {
            prop: 'carConfigCN',
            label: '基础车型'
          },
          {
            prop: 'carColorName',
            label: '车身颜色'
          },
          {
            prop: 'carIncolorName',
            label: '内饰颜色'
          },
          {
            prop: 'optionalPagName',
            label: '选装包'
          },
          {
            prop: 'price',
            label: '价格'
          },
          {
            prop: 'invoiceCustName',
            label: '企业名称'
          },
          {
            prop: 'invoiceCustPhone',
            label: '联系电话'
          },
          {
            prop: 'invoiceCustCredCode',
            label: '社会信用代码'
          }
        ],
      // 字段格式化转换（用于导出excel）（kvs表示键值转换）
      // dynamicExportConverts: {
      //   'isForce': {
      //     'convert': 'kvs',
      //     'kvs': {
      //       '1': '是',
      //       '0': '否'
      //     }
      //   }
      // },
      // 单表格模版页面组件回调事件
      callbackObj: {
        // 当选择项发生变化时会触发该事件（多选时）
        onCheckSelectChange: (selection) => {
          this.selectList = selection
          this.handleSelectionChange(selection)
        },
        onBeforeQuery: (ops) => {
          // 不兼容字段 转换
          const ss = [
            ['insaleOrderStatus', 'orderStatus'],
            ['optionalPagId', 'carOptionalpagId'],
            ['carStockHouseId', 'carHouseId'],
            ['dlrId', 'saleDlrId']
          ]
          ss.forEach(arr => {
            ops.variables[arr[1]] = ops.variables[arr[0]]
            delete ops.variables[arr[0]]
          })
        }

      },
      exportPopups: false
    }
  },
  watch: {
    'formField.carSeriesId': {
      handler(val) {
        if (!val) {
          this.formField.carConfigId = ''
        }
      }
    },
    'formField.carConfigId': {
      handler(val) {
        if (!val) {
          this.formField.optionalPagId = ''
          this.formField.carColorId = ''
          this.formField.carIncolorId = ''
        }
      }
    }
  },
  created() {
    this.genCodeFiled = this.genUtil(this.tableComponents)
    const formField = this.genCodeFiled('codeField')
    // this.formField = this.$utils.getFormField(this, formField, this.$ConfigCache.CacheConfig.cacheData[viewPageCode])
    this.formField = formField
  },
  mounted() {
    // 列表查询
    this.queryTable(1)
  },
  methods: {
    getConfigData(data) {
      console.log(data)
    },
    // 批量手动配车
    configCar() {
      let openFlag = true
      this.selectList.every(item => {
        if (item.OrderStatus !== '合同已签署') {
          openFlag = false
          return false
        }
        return true
      })
      if (openFlag) {
        this.batchData = this.$utils.deepCopy(this.selectList)
        this.curPopupsVisible1 = openFlag
      } else {
        this.$confirm('合同已签署才能进行批量手动配车，请重新选择！', this.$t('org.label.warnning')/* 提示*/, {
          cancelButtonText: this.$t('org.label.cancel')/* 取消*/,
          confirmButtonText: this.$t('org.label.confirm')/* 确认*/,
          type: 'warning'
        }).then(() => { })
      }
    },
    // 导入配车
    exportConfigCar() {
      this.exportPopups = true
    },
    // 尾款确认
    tailConfig() {
      let openFlag = true
      this.selectList.every(item => {
        if (item.OrderStatus !== '车辆验收入库') {
          openFlag = false
          return false
        } else {
          return true
        }
      })
      // 选中的全是验收入库的
      if (openFlag) {
        const data = this.selectList.reduce((array, cur) => {
          array.push({
            saleOrderId: cur.saleOrderId,
            updateControlId: cur.updateControlId
          })
          return array
        }, [])
        this.$requestAPI({
          apiUrl: api.oDcConfirmBill.APIUrl,
          variables: {
            exportData: data
            // saleOrderId: this.selectList.map(o => o.saleOrderId),
            // updateControlId: this.selectList.map(o => o.updateControlId)
          }
        }).then(response => {
          if (response.result === '1') {
            if (response.msg) {
              this.$message(response.msg)
            } else {
              this.$message('尾款已确认!')
            }
            this.queryTable()
          } else {
            this.$message(response.msg)
          }
        }).catch(err => {
          if (err.response.data.msg) {
            this.$message(err.response.data.msg)
          } else {
            this.$message(err.message)
          }
        })
      } else {
        this.$confirm('验收入库才能进行尾款确认，请重新选择！', this.$t('org.label.warnning')/* 提示*/, {
          cancelButtonText: this.$t('org.label.cancel')/* 取消*/,
          confirmButtonText: this.$t('org.label.confirm')/* 确认*/,
          type: 'warning'
        }).then(() => { })
      }
    },
    // 解佩
    depp(index) {
      const { saleOrderId, updateControlId, updateControlIdD, SALE_ORDER_D_ID, vin,
        updateControlIdS, carStoreId, updateControlIdE, salePlanCode
      } = this.$refs['multipleTable'].list[index]
      this.$confirm('确定要解配此订单吗？', '提示')
        .then(() => {
          this.$requestAPI({
            apiUrl: api.delCAForTestDrive.APIUrl,
            variables: { saleOrderId, updateControlId, updateControlIdD, SALE_ORDER_D_ID, vin,
              updateControlIdS, carStoreId, updateControlIdE, salePlanCode }
          }).then(res => {
            if (res.result === '1') {
              res.msg ? this.$message(res.msg) : this.$message('解配成功!')
              this.queryTable(1)
              this.$emit('update:popupsVisible', false)
            } else {
              this.$message(res.msg)
            }
          }).catch(err => {
            if (err.response.data.msg) {
              this.$message(err.response.data.msg)
            } else {
              this.$message(err.message)
            }
          })
        })
    },
    // 导出excel
    export() {
      var dateObj = this.$utils.deepCopy(this.formField)
      console.log(dateObj)
      const ss = [
        ['insaleOrderStatus', 'orderStatus'],
        ['optionalPagId', 'carOptionalpagId'],
        ['carStockHouseId', 'carHouseId'],
        ['dlrId', 'saleDlrId']
      ]
      ss.forEach(arr => {
        dateObj[arr[1]] = dateObj[arr[0]]
        delete dateObj[arr[0]]
      })
      exportExcel.call(this,
        api.orderDistributeCarExport.APIUrl,
        null,
        dateObj
      )
    },
    // 自动生成codeField
    genUtil: (array) => (attr) => array.reduce((p, c) => { p[c[attr]] = ''; return p }, {}),
    // 保存 或新增 后会调用此方法
    popClose(type) {
      this.showdia = false
      if (type === 1) {
        this.queryTable(1)
      }
    },
    // 当选择项发生变化时会触发该事件
    handleSelectionChange(selection) {
      const btns = this.dynamicButtons.filter(o => o.disabled !== undefined)
      if (btns.length > 0) {
        const isCheck = selection && selection.length > 0
        btns.forEach((item) => {
          item.disabled = !isCheck
        })
      }
    },

    hiddenColData(data) {
      if (data && data.length > 0) {
        this.refreshTableKey += 1
        this.dynamicTableCols = data
      }
    },

    // 新增
    // add() {
    //   this.clickRowsData = {}
    //   this.popstate = 'add'
    //   this.showdia = true
    // },
    //
    // 手动配车
    edit(index) {
      this.rowData = this.$utils.deepCopy(this.$refs['multipleTable'].list[index])
      this.curPopupsVisible = true
    },
    selectRowsData(rowdata) {

    },

    // 查看附件
    checkFile(index, type) {
      // location.href = process.env.VUE_APP_BASE_API + this.$refs['multipleTable'].list[index].downloadUrl
      window.open(this.$refs['multipleTable'].list[index][type])
    },

    // 删除按钮单条删除
    delOneData(row) {
      const data = [this.$refs['multipleTable'].list[row]]
      this.delData(data)
    },

    // 数据批量删除
    delSeleteData() {
      const data = this.$refs['multipleTable'].$refs['multipleTable'].selection
      this.delData(data)
    },

    // 删除
    delData(selectData) {
      this.$confirm('确定要作废选中订单吗?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // requestRestful({
        //   apiUrl: '',
        //   variables: {},
        //   method: 'POST', // 默认post
        //   contentType: '', // 默认 'application/json; charset=UTF-8'
        //   lock: '',
        //   urlType: 'GET' // 处理非json请求
        // })
      }).catch(() => {})
    }
  }
}
</script>

